//
//  DeviceViewController.m
//  ZhongKeXinHeater
//
//  Created by Kendama on 2017/6/1.
//  Copyright © 2017年 DT. All rights reserved.
//

#import "DeviceListViewController.h"
#import "PublicGetUserDeviceApi.h"
#import "PublicGetADListApi.h"
#import "SCAdView.h"
#import "HeroModel.h"
#import "PublicGetMessageListApi.h"

@interface DeviceListViewController ()<SDCycleScrollViewDelegate,UITableViewDataSource,UITableViewDelegate,MGSwipeTableCellDelegate,SCAdViewDelegate>

@property (nonatomic, strong) UITableView *tableView;

/** 图片轮播器 **/
//@property(nonatomic,strong) SDCycleScrollView *cycleScrollView;
@property(nonatomic,strong) SCAdView *adView;


/** 空数据提示 */
@property (nonatomic,strong) UILabel *emptyLabel;

@end

@implementation DeviceListViewController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(deviceStatusChange:) name:NOTIFY_ONLINESTATUS_CHANGE object:nil];
    

}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self.tableView reloadData];
    
    [self updateMessage];
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [AppDelegate defaultAppDelegate].currentDevice = nil;
    [self updateDeviceList];
}

- (void)refreshBaseControlValue
{
    
    [self setNavigationTitle:@"设备" titleColor:[UIColor blackColor]];
    self.navigationBar.backgroundColor = [UIColor colorWithHexString:@"D0D0D0"];
    [self setRightButtonImage:[UIImage imageNamed:@"nav_add"]];
    
    [self masLayoutSubviews];
    
    [self loadADImageView];
}


#pragma mark -- 事件
- (void)deviceStatusChange:(NSNotification *)notify
{
    NSDictionary *onlineDic = notify.object;
    if ([onlineDic isKindOfClass:[NSDictionary class]]) {
        
        for (DTDevice *device in [[AppDelegate defaultAppDelegate]deviceList]) {
            if ([device.macAddress isEqualToString:onlineDic[@"macAddress"]]) {
                device.isOnline = [onlineDic[@"isonline"]boolValue];
                [self.tableView reloadData];
                break;
            }
        }
    }
}

// 调用服务器接口防止Token失效
- (void)updateMessage
{
    PublicGetMessageListApi *api = [[PublicGetMessageListApi alloc]initWithDic:@{@"device_type":@"0",@"page":@"0"}];
    [api dtDefaultInterceptStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {
        
    } failure:^(YTKBaseRequest * _Nonnull request) {
        
    }];
;
}

- (void)loadADImageView{
    PublicGetADListApi *api = [[PublicGetADListApi alloc] init];
    [api dtDefaultInterceptStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {
        NSDictionary *dic = [request responseJSONObject];
        if ([dic[@"errcode"] intValue] == 0) {
            NSArray *array = dic[@"data"];
            NSString *domain = dic[@"domain"];
            NSMutableArray *data = [[NSMutableArray alloc] init];
            for (NSString *string in array) {
                NSString *urlString = [NSString stringWithFormat:@"%@/%@",domain,string];
                HeroModel *hero = [HeroModel new];
                hero.imageName = urlString;
                [data addObject:hero];
            }
            
            self.adView = [self.adView initWithBuilder:^(SCAdViewBuilder *builder) {
                builder.allowedInfinite = YES;  //非必要参数 ：设置不无限循环轮播,默认为Yes
                builder.adArray = data;
                builder.viewFrame = (CGRect){0,64,self.view.bounds.size.width,self.view.bounds.size.width/2.f};
                builder.adItemSize = (CGSize){px1080Width(710),px1920Height(424)};
                builder.minimumLineSpacing = px1080Width(33);
                builder.secondaryItemMinAlpha = 1;
                builder.threeDimensionalScale = 0;//1.45
                builder.itemCellNibName = @"SCAdDemoCollectionViewCell";
            }];
            self.adView.backgroundColor = [UIColor whiteColor];
        
            
        } else {
            [SVProgressHUD showErrorWithStatus:dic[@"errmsg"]];
        }
        
    } failure:nil];
}

- (void)updateDeviceList
{
    /*
     *  获取对应账号所绑定的设备，需确保用户登录了
     */
    [[DTCloudManager defaultJNI_iOS_SDK]getAllDeviceSuccessCallback:^(NSArray *deviceList) {
        
        [[AppDelegate defaultAppDelegate].deviceList removeAllObjects];
        [[AppDelegate defaultAppDelegate].deviceList addObjectsFromArray:deviceList];
        
        MAIN(^{
//            [self updateUserDeviceList];
        });
        
        if ([[AppDelegate defaultAppDelegate].deviceList count] == 0) {
            self.emptyLabel.hidden = NO;
        } else {
            self.emptyLabel.hidden = YES;
        }
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
    } errorCallback:^(NSDictionary *dic) {
        [[AppDelegate defaultAppDelegate].deviceList removeAllObjects];
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        [SVProgressHUD showInfoWithStatus:dic[@"errmsg"]];
    }];
}


#pragma mark -- 点击事件
- (void)onRightButtonClick:(id)sender {
    self.hidesBottomBarWhenPushed = YES;
    AddDeviceViewController *vc = [[AddDeviceViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
    self.hidesBottomBarWhenPushed = NO;

}






#pragma mark -- 代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [AppDelegate defaultAppDelegate].deviceList.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return px1920Height(154);
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DTDevice *device = [[AppDelegate defaultAppDelegate].deviceList objectAtIndex:indexPath.row];
    DeviceTableViewCell *cell = [DeviceTableViewCell cellWithTableView:tableView];
    cell.deivce = device;
    MGSwipeButton *deleteButton = [MGSwipeButton buttonWithTitle:@"" icon:[UIImage imageNamed:@"icon_delete"] backgroundColor:[UIColor blackColor] callback:^BOOL(MGSwipeTableCell *sender) {
        [[AlertViewManager shareManager]initWithMessage:@"是否确认删除该设备？" cancleButtonTitle:@"取消" OtherButtonsArray:@[@"确认"] clickAtIndex:^(NSInteger buttonIndex, UIAlertView *alertView) {
            if (buttonIndex == 1) {
                [tableView reloadData];
                [[DTCloudManager defaultJNI_iOS_SDK]unBindDeviceByUUID:device.deviceUUID successCallback:^(NSDictionary *dic) {
                    [SVProgressHUD showInfoWithStatus:@"解绑成功" maskType:SVProgressHUDMaskTypeBlack];
                    [self updateDeviceList];
                } errorCallback:^(NSDictionary *dic) {
                    [SVProgressHUD showInfoWithStatus:@"解绑失败" maskType:SVProgressHUDMaskTypeBlack];
                }];
            }
         
        }];
        return YES;
    }];
    MGSwipeButton *editButton = [MGSwipeButton buttonWithTitle:@"" icon:[UIImage imageNamed:@"icon_edit"] backgroundColor:[UIColor lightGrayColor] callback:^BOOL(MGSwipeTableCell *sender) {
        [[AlertViewManager shareManager]initWithEditActionTitle:@"重命名" message:nil cancleButtonTitle:@"取消" OtherButtonsArray:@[@"确认"] clickAtIndex:^(NSInteger buttonIndex, UIAlertView *alertView) {
            if (buttonIndex == 1) {
                if ([alertView textFieldAtIndex:0].text.length == 0) {
                    [SVProgressHUD showInfoWithStatus:@"名字不能为空"];
                    return;
                }
                if ([alertView textFieldAtIndex:0].text.length > 20) {
                    [SVProgressHUD showInfoWithStatus:@"名字长度不能超过20个"];
                    return;
                }
                
                if ([self isContainsTwoEmoji:[alertView textFieldAtIndex:0].text] ) {
                    [SVProgressHUD showInfoWithStatus:@"名字不能使用表情"];
                    return;
                }
                [[DTCloudManager defaultJNI_iOS_SDK] renameDeviceByUUID:device.deviceUUID andDeviceName:[alertView textFieldAtIndex:0].text successCallback:^(NSDictionary *dic) {
                    [SVProgressHUD showSuccessWithStatus:dic[@"errmsg"] maskType:SVProgressHUDMaskTypeBlack];
                    [self updateDeviceList];
                } errorCallback:^(NSDictionary *dic) {
                    [SVProgressHUD showInfoWithStatus:dic[@"errmsg"] maskType:SVProgressHUDMaskTypeBlack];

                }];

            }
  

        }];
        return YES;
    }];
    
    cell.rightButtons = @[deleteButton,editButton];
    
    // 分割线对齐左边
    cell.separatorInset = UIEdgeInsetsZero;
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]){
        [cell setPreservesSuperviewLayoutMargins:NO];
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    DTDevice *device = [[AppDelegate defaultAppDelegate].deviceList objectAtIndex:indexPath.row];
    if (!device.isOnline) {
        [SVProgressHUD showInfoWithStatus:@"设备处于离线状态"];
        return;
    }
    
    [AppDelegate defaultAppDelegate].currentDevice = device;
    self.hidesBottomBarWhenPushed = YES;
    DeviceViewController *vc = [[DeviceViewController alloc] init];
    vc.title = device.deviceName;
    [self.navigationController pushViewController:vc animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}



/** 点击图片回调 */
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
    
}

/** 图片滚动回调 */
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didScrollToIndex:(NSInteger)index{
    
}

// 广告页代理
-(void)sc_didClickAd:(id)adModel{
    NSLog(@"sc_didClickAd-->%@",adModel);
    if ([adModel isKindOfClass:[HeroModel class]]) {
//        NSLog(@"%@",((HeroModel*)adModel).introduction);
    }
}

-(void)sc_scrollToIndex:(NSInteger)index{
//    NSLog(@"sc_scrollToIndex-->%ld",index);
}

- (BOOL)isContainsTwoEmoji:(NSString *)string
{
    __block BOOL isEomji = NO;
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:
     ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
         const unichar hs = [substring characterAtIndex:0];
         if (0xd800 <= hs && hs <= 0xdbff) {
             if (substring.length > 1) {
                 const unichar ls = [substring characterAtIndex:1];
                 const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                 if (0x1d000 <= uc && uc <= 0x1f77f)
                 {
                     isEomji = YES;
                 }
             }
         } else if (substring.length > 1) {
             const unichar ls = [substring characterAtIndex:1];
             if (ls == 0x20e3|| ls ==0xfe0f) {
                 isEomji = YES;
             }
         } else {
             if (0x2100 <= hs && hs <= 0x27ff && hs != 0x263b) {
                 isEomji = YES;
             } else if (0x2B05 <= hs && hs <= 0x2b07) {
                 isEomji = YES;
             } else if (0x2934 <= hs && hs <= 0x2935) {
                 isEomji = YES;
             } else if (0x3297 <= hs && hs <= 0x3299) {
                 isEomji = YES;
             } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50|| hs == 0x231a ) {
                 isEomji = YES;
             }
         }
         
     }];
    return isEomji;
}



#pragma mark -- 懒加载

- (SCAdView *)adView
{
    if(!_adView)
    {
        UIView *superView = self.view;
        NSArray *testArray =@[@"banner",@"banner",@"banner",@"banner"];
         
        _adView = [[SCAdView alloc]initWithBuilder:^(SCAdViewBuilder *builder) {
            builder.allowedInfinite = YES;  //非必要参数 ：设置不无限循环轮播,默认为Yes
            builder.adArray = testArray;
            builder.viewFrame = (CGRect){0,64,self.view.bounds.size.width,self.view.bounds.size.width/2.f};
            builder.adItemSize = (CGSize){px1080Width(710),px1920Height(424)};
            builder.minimumLineSpacing = 0;
            builder.secondaryItemMinAlpha = 1;
            builder.threeDimensionalScale = 0;//1.45
            builder.itemCellNibName = @"SCAdDemoCollectionViewCell";
        }];
        _adView.backgroundColor = [UIColor whiteColor];
        _adView.delegate = self;
        [superView addSubview:_adView];
        
        
    }
    return _adView;
}


- (UITableView *)tableView
{
    if(!_tableView)
    {
        UIView *superView = self.view;
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(updateDeviceList)];
        [superView addSubview:_tableView];
    }
    return _tableView;
}

- (UILabel *)emptyLabel{
    
    if (!_emptyLabel) {
        _emptyLabel = [[UILabel alloc]init];
        _emptyLabel.text = @"未接入设备，请接入设备后使用";
        _emptyLabel.font = [UIFont systemFontOfSize:px1080Width(42)];
        _emptyLabel.textColor = [UIColor colorWithRed:151/255.0 green:151/255.0 blue:151/255.0 alpha:1];
        [self.view addSubview:_emptyLabel];
    }
    return _emptyLabel;
}


#pragma mark -- 初始化
- (void)masLayoutSubviews{
    __weak UIView *superView = self.view;
    [self.adView play];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.adView.mas_bottom).with.offset(px1920Height(58));
        make.width.equalTo(superView);
        make.bottom.equalTo(superView).with.offset(-49);
    }];
    
    
    [self.emptyLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.centerY.equalTo(self.view).with.offset(px1920Height(200));
    }];
    
    self.emptyLabel.hidden = YES;
}

@end
